package org.joinme.backend.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpException;
import org.joinme.backend.util.ApiHttp;
import org.joinme.backend.util.ErrorCodeMsg;
import org.joinme.backend.util.PrjException;
import org.joinme.backend.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class WechatService {
    private Cache tokenCache;

    private Map<String, String> wxAppIds = new HashMap<>();
    private Map<String, String> wxSerects = new HashMap<>();

    @Autowired
    public WechatService(EhCacheCacheManager cacheManager) {
        tokenCache = cacheManager.getCache("token");

        wxAppIds.put("jm", "wx032e68e0566fa345");
        wxSerects.put("jm", "2d13152e4ae85c666000401c70d8c081");

    }

    private JSONObject getSessionKeyAndIdByCode(String code, String appName) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxAppIds.get(appName) + "&secret=" + wxSerects.get(appName) + "&js_code=" + code + "&grant_type=authorization_code";
        JSONObject ret = JSONObject.parseObject(ApiHttp.doGet(url));

        return ret;
    }

    public String getOpenIdByCode(String code, String appName) throws PrjException {
        JSONObject requestRet = getSessionKeyAndIdByCode(code, appName);

        if(requestRet.getIntValue("errcode") > 0)
            throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_CODE_ERROR);

        String openId = requestRet.getString("openid");
        if(StringUtil.isEmpty(openId))
            throw new PrjException(ErrorCodeMsg.USER_WECHAT_LOGIN_CODE_ERROR);

        return appName + "-" + openId;
    }

    public String getAccessToken(String appName) throws HttpException, IOException {
        String key = "accessToken";

        String accessToken = tokenCache.get(key, String.class);
        if (!StringUtil.isEmpty(accessToken)) {
            return accessToken;
        }

        // 获取accessToken start
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + wxAppIds.get(appName) + "&secret=" + wxSerects.get(appName);
        String responseJsonData = ApiHttp.doGet(accessTokenUrl);
        JSONObject jsonData = JSON.parseObject(responseJsonData);
        accessToken = jsonData.getString("access_token");

        //将token放到缓存当中
        if (!StringUtil.isEmpty(accessToken)) {
            tokenCache.put(key, accessToken);
        }

        return accessToken;
    }


}
